import { getSearchAPI, getSearchResultAPI } from '@/api/search';
import { AppDispatch } from '../index';

export const getSearchAction = (q: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await getSearchAPI(q);
    console.log('res  ----->  ', res);
    dispatch({ type: 'search/saveSuggest', payload: res.data.options });
  };
};

export const clearSuggestAction = () => {
  return {
    type: 'search/saveSuggest',
    payload: [],
  };
};

export const saveHistoriesAction = (keyword: string) => {
  return {
    type: 'search/saveHistories',
    payload: keyword,
  };
};

export const clearHistoriesAction = () => {
  return {
    type: 'search/clearHistories',
  };
};

export const getSearchResultAction = (q: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await getSearchResultAPI({ q });
    console.log('res  ----->  ', res);
    dispatch({ type: 'search/saveResults', payload: res.data });
  };
};

export const updateSearchResultAction = (
  q: string,
  page: number,
  per_page = 10
) => {
  return async (dispatch: AppDispatch) => {
    const res = await getSearchResultAPI({ q, page });
    console.log('res  ----->  ', res);
    dispatch({ type: 'search/updateResults', payload: res.data });
  };
};
